<!--
 * @Descripttion: 编辑明星资料
 * @Author: xiao li
 * @Date: 2020-12-23 16:00:02
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-23 15:45:50
-->
<template>
  <div class="lb-websit-edit-video">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <div style="height: 20px"></div>
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="subForm"
        label-width="120px"
      >
        <el-form-item label="姓名" prop="title">
          <el-input
            v-model="subForm.title"
            maxlength="20"
            show-word-limit
            placeholder="请输入姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 330 * 330</lb-tool-tips>
        </el-form-item>
        <el-form-item label="轮播图" prop="imgs">
          <lb-cover
            type="more"
            :fileList="subForm.imgs"
            @selectedFiles="selectedFiles($event, 'imgs')"
            @moveFiles="moveFiles($event, 'imgs')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 750</lb-tool-tips>
        </el-form-item>
        <el-form-item label="所属分类" prop="cate_id">
          <el-cascader
            v-model="subForm.cate_id"
            :options="cateList"
            :props="{ checkStrictly: true, label: 'title', value: 'id' }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="地区">
          <el-select
            v-model="subForm.choose[0].list"
            multiple
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in screenList[0].list"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select
            v-model="subForm.choose[1].list"
            multiple
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in screenList[1].list"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职业">
          <el-select
            v-model="subForm.choose[2].list"
            multiple
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in screenList[2].list"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <el-select
            v-model="subForm.choose[3].list"
            multiple
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in screenList[3].list"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="相关推荐">
          <el-select
            v-model="subForm.recommend"
            multiple
            filterable
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in starList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关注度" prop="star">
          <el-input-number
            class="lb-input-number"
            v-model.number="subForm.star"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入关注度"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="跳转链接" prop="is_link">
          <el-radio-group v-model="subForm.is_link">
            <el-radio :label="0">{{ $t('action.OFF') }}</el-radio>
            <el-radio :label="1">{{ $t('action.ON') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="链接类型"
          prop="link_type"
          v-show="subForm.is_link === 1"
        >
          <el-select
            @change="changeLinkType"
            v-model="subForm.link_type"
            placeholder="请选择"
          >
            <el-option
              v-for="(citem, cindex) in link_options"
              :key="cindex"
              :label="citem.label"
              :value="citem.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="link" v-show="subForm.is_link === 1">
          <el-tag
            v-if="subForm.link_type === 4"
            :closable="cur_info.title ? true : false"
            @close="delCurInfo"
            @click="open"
            >{{ cur_info.title || '选择链接' }}</el-tag
          >
          <el-input
            v-model="subForm.link"
            :placeholder="jumpType[subForm.link_type]"
            v-else
          ></el-input>

          <lb-tool-tips
            >小程序跳转链接填写格式如下:
            <div class="mt-md">
              1、跳转到小程序首页
              <div class="mt-md c-link">
                所需参数如下：
                <div class="mt-sm">[1] appId</div>
              </div>
              <div class="mt-md">例如：wx581f0c1732ae745f</div>
            </div>
            <div class="mt-lg">
              2、跳转到小程序指定页面
              <div class="mt-md c-link">
                所需参数如下：
                <div class="mt-sm">[1] appId</div>
                <div class="mt-sm">[2] ; (英文状态下的分号)</div>
                <div class="mt-sm">[3] 页面路径及参数</div>
              </div>
              <div class="mt-md">
                例如：wx581f0c1732ae745f;pages/user/home?key=1&staff_id=1
              </div>
            </div>
          </lb-tool-tips>
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item label="简介" prop="content">
          <lb-ueditor v-model="subForm.content" :destroy="true"></lb-ueditor>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitFormInfo('subForm')">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>

      <!-- 选择可用链接 -->

      <el-dialog
        title="选择链接"
        :visible.sync="visible"
        width="800px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :append-to-body="true"
      >
        <div v-loading="loading">
          <div class="dialog-module-list">
            <div
              class="dialog-module-item"
              :class="{ 'dialog-module-item--select': index == activeIndex }"
              v-for="(item, index) in moduleList"
              :key="index"
              @click="moduleClick(index)"
            >
              {{ item.title }}
            </div>
          </div>
          <div style="display: flex" v-if="moduleList.length > 0">
            <div class="dialog-left">
              <div class="dialog-left_title">
                {{ moduleList[activeIndex].title }}链接
              </div>
              <div
                class="dialog-left_item"
                :class="{ 'dialog-left_item--select': aindex == cactiveIndex }"
                v-for="(aitem, aindex) in moduleList[activeIndex].data"
                :key="aindex"
                @click="moduleChildClick(aindex)"
              >
                {{ aitem.title }}
              </div>
            </div>
            <div
              style="flex: 1"
              v-if="moduleList[activeIndex].data[cactiveIndex].api_path"
            >
              <div
                class="text-right mb-lg"
                v-if="
                  moduleList[activeIndex].data[cactiveIndex].page !==
                  'common_page'
                "
              >
                <el-input
                  v-model="searchForm.keyword"
                  placeholder="请输入名称搜索"
                  size="small"
                ></el-input>
                <el-button
                  type="primary"
                  @click="search"
                  size="small"
                  style="margin-left: 10px"
                  >搜索</el-button
                >
              </div>

              <el-table
                ref="singleTable"
                :data="tableData"
                :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
                @current-change="handleCurrentChange"
                v-loading="tableLoading"
                :highlight-current-row="true"
              >
                <el-table-column
                  prop="id"
                  label="ID"
                  width="150"
                  v-if="
                    moduleList[activeIndex].data[cactiveIndex].page !==
                    'common_page'
                  "
                ></el-table-column>
                <el-table-column prop="title" label="名称"></el-table-column>
              </el-table>
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer-diy">
          <div class="dialog-footer_op">
            <el-button @click="visible = false">取 消</el-button>
            <el-button type="primary" @click="submit">确 定</el-button>
          </div>
          <el-pagination
            v-if="
              moduleList.length > 0 &&
              moduleList[activeIndex].data[cactiveIndex].api_path &&
              moduleList[activeIndex].data[cactiveIndex].page !== 'common_page'
            "
            @size-change="handleSizeChange"
            @current-change="handlePageCurrentChange"
            :total="total"
            :current-page="searchForm.page"
            :page-size="searchForm.page_count"
            :page-sizes="[5, 10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
          ></el-pagination>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { get } from '../../../../api/index'
export default {
  data () {
    let validateLink = (rule, value, callback) => {
      let { is_link: isLink, link, link_type: type } = this.subForm
      if (isLink === 1 && !link) {
        callback(new Error(this.jumpType[type]))
      } else {
        callback()
      }
    }
    return {
      navTitle: '',
      link_options: [{ label: '系统内部页面', value: 4 }, { label: '其他小程序', value: 2 }, { label: '跳转网页', value: 3 }, { label: '拨打电话', value: 1 }],
      jumpType: {
        1: '请输入电话号码', 2: '请输入小程序appid', 3: '请输入网页链接', 4: '请选择系统内部链接'
      },
      cur_info: { title: '', url: '' },
      visible: false,
      moduleList: [],
      activeIndex: 0,
      cactiveIndex: 0,
      currentRow: {},
      searchForm: {
        page: 1,
        limit: 10,
        page_count: 10,
        keyword: '',
        status: 1,
        diy_id: 0,
        key: 2
      },
      total: 0,
      loading: false,
      tableLoading: false,
      cateList: [],
      screenList: [{ list: [], type: 1 }, { list: [], type: 2 }, { list: [], type: 3 }, { list: [], type: 4 }],
      starList: [],
      subForm: {
        id: 0,
        modular_id: 0,
        title: '',
        cover: '',
        imgs: [],
        cate_id: [],
        choose: [{ list: [], type: 1 }, { list: [], type: 2 }, { list: [], type: 3 }, { list: [], type: 4 }],
        recommend: [],
        star: '',
        content: '',
        is_link: 0,
        link_type: 1,
        link_title: '',
        link: '',
        top: 0,
        status: 1
      },
      subFormRules: {
        title: {
          required: true,
          type: 'string',
          message: '请输入姓名',
          trigger: 'blur'
        },
        cover: {
          required: true,
          type: 'array',
          message: '请上传图片',
          trigger: 'change'
        },
        imgs: {
          required: true,
          type: 'array',
          message: '请上传图片',
          trigger: 'change'
        },
        cate_id: {
          required: true,
          type: 'array',
          message: '请选择分类',
          trigger: 'change'
        },
        is_link: {
          required: true,
          type: 'number',
          message: '请选择',
          trigger: 'blur'
        },
        link_type: {
          required: true,
          type: 'number',
          message: '请选择',
          trigger: 'blur'
        },
        link: {
          required: true,
          validator: validateLink,
          trigger: 'blur'
        },
        top: {
          required: true,
          type: 'number',
          message: '请输入排序值',
          trigger: 'blur'
        },
        content: {
          required: true,
          type: 'string',
          message: '请输入简介',
          trigger: 'change'
        }
      }
    }
  },
  created () {
    let { modular_id: mid, id = 0 } = this.$route.query
    this.subForm.modular_id = mid
    this.subForm.id = id
    this.navTitle = this.$t(id ? 'menu.WebsiteOfferStarEdit' : 'menu.WebsiteOfferStarAdd')
    this.getBaseInfo()
    if (!id) return
    this.getDetail()
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    /**
     * @method 获取分类/筛选
     */
    async getBaseInfo () {
      let { modular_id: mid, id = 0 } = this.subForm
      let [{ code: classifyCode, data: classifyData }, { code: starCode, data: starData }, { code: screenCode, data: screenData }] = await Promise.all([this.$api.websiteStarCateSelect({ modular_id: mid }), this.$api.websiteStarSelect({ modular_id: mid, id }), this.$api.websiteStarAllChooseSelect({ modular_id: mid })])
      if (classifyCode === 200) {
        this.cateList = classifyData
      }
      if (starCode === 200) {
        this.starList = starData
      }
      if (screenCode === 200) {
        this.screenList = screenData
      }
    },
    getDetail () {
      let { modular_id: mid, id } = this.subForm
      this.$api.websiteStarInfo({ modular_id: mid, id }).then(res => {
        if (res.code === 200) {
          res.data.cover = [{ url: res.data.cover }]
          res.data.imgs = res.data.imgs.map(item => {
            return { url: item }
          })
          for (let key in this.subForm) {
            this.subForm[key] = res.data[key]
          }
          if (res.data.link_type !== 4) return
          this.cur_info = {
            title: res.data.link_title,
            url: res.data.link
          }
        }
      })
    },
    getCover (img) {
      this.subForm.cover = img
    },
    selectedFiles (imgs, key) {
      this.subForm[key].push(...imgs)
    },
    moveFiles (imgs, key) {
      this.subForm[key] = imgs
    },
    changeLinkType (e) {
      let { title = '', url = '' } = this.cur_info
      this.subForm.link = e === 4 ? url : ''
      this.subForm.link_title = e === 4 ? title : ''
    },
    handleCurrentChange (val) {
      this.currentRow = val
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.searchForm.page_count = val
      this.handlePageCurrentChange(1)
    },
    handlePageCurrentChange (val) {
      this.searchForm.page = val
      this.getList()
    },
    submit () {
      let moduleItem = this.moduleList[this.activeIndex]
      if (!moduleItem) {
        this.$message.error('请选择')
        return
      }
      let item = moduleItem.data[this.cactiveIndex]
      if (!item) {
        this.$message.error('请选择')
        return
      }
      let obj = {
        title: item.title,
        url: item.page
      }
      if (item.api_path) {
        if (!this.currentRow) {
          this.$message.error('请点击列表选择一项')
          return
        } else {
          let { id = 0, title = '' } = this.currentRow
          obj.title = title || '无标题'
          let arr = ['common_page']
          let arr2 = ['/pages/shop/detail']
          let curURL = obj.url
          obj.url = `${curURL}?id=${id}&title=${title}`
          if (arr.includes(curURL)) {
            obj.url = `${this.currentRow.path}`
          }
          if (arr2.includes(curURL)) {
            obj.url = `${curURL}?id=${id}&staff_id=`
          }
          if (curURL === '/pages/website/list') {
            let { type, content = '' } = this.currentRow
            let linkType = type === 6 ? 1 : type === 10 ? 2 : type === 9 ? 3 : 4
            let modularId = this.currentRow.modular_id || 0
            obj.url = linkType === 4 ? type === 11 && modularId ? `/website/pages/cate?id=${id}&modular_id=${modularId}&name=${title}&mtype=${type}` : `${curURL}?id=${id}&name=${title}&mtype=${type}` : `${content}`
            obj.url = `${obj.url}&link_type=${linkType}`
          }
        }
      }
      this.cur_info = obj
      this.subForm.link = obj.url
      this.subForm.link_title = obj.title
      this.visible = false
    },
    moduleClick (index) {
      this.activeIndex = index
      this.cactiveIndex = 0
      this.searchForm.page = 1
      this.searchForm.limit = 10
      this.searchForm.page_count = 10
      this.searchForm.keyword = ''
      this.getList()
    },
    moduleChildClick (index) {
      this.cactiveIndex = index
      this.searchForm.page = 1
      this.searchForm.limit = 10
      this.searchForm.page_count = 10
      this.searchForm.keyword = ''
      this.getList()
    },
    search () {
      this.searchForm.page = 1
      this.getList()
    },
    async open () {
      this.visible = true
      this.loading = true
      let res = await this.$api.getMoudelByKey({ key: '2,4' })
      this.loading = false
      if (res.code === 200) {
        this.moduleList = res.data
        this.getList()
      }
    },
    async getList () {
      let item = this.moduleList[this.activeIndex].data[this.cactiveIndex]
      if (!item.api_path) {
        this.tableData = []
        this.total = 0
        return
      }
      let searchForm = JSON.parse(JSON.stringify(this.searchForm))
      if (item.page === 'common_page') {
        searchForm.diy_id = this.routesItem.diyID
        searchForm.key = this.moduleList[this.activeIndex].key
      }
      this.tableLoading = true
      let res = await get(item.api_path, searchForm)
      this.tableLoading = false
      if (res.code === 200) {
        this.tableData = res.data.data
        this.total = res.data.total
      }
    },
    delCurInfo () {
      this.cur_info = { title: '', url: '' }
    },
    /**
     * @method 提交表单信息
     */
    submitFormInfo (name) {
      let title = JSON.parse(JSON.stringify(this.subForm.title)).replace(/^\s+|\s+$/g, '')
      this.subForm.title = title
      this.$refs[name].validate(valid => {
        if (valid) {
          let subForm = JSON.parse(JSON.stringify(this.subForm))
          let count = 0
          subForm.choose.map(item => {
            count += item.list.length
          })
          if (!count) {
            this.$message.error(`请选择地区/分类/职业/年龄，至少关联一个选项`)
            return
          }
          subForm.cover = subForm.cover[0].url
          subForm.imgs = subForm.imgs.map(item => {
            return item.url
          })
          let methodModel = subForm.id ? 'websiteStarUpdate' : 'websiteStarAdd'
          this.$api[methodModel](subForm).then(res => {
            if (res.code === 200) {
              this.$message.success(this.$t('tips.successSub'))
              this.$router.back(-1)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-websit-edit-video {
  width: 100%;
  .page-main {
    width: 100%;
    .el-input,
    .el-input-number,
    .el-select,
    .el-cascader {
      width: 300px;
    }
  }
}
</style>
